package shaka.core.internal

/**
 * Java Bean 轉換物件
 * 
 * @author Shaka
 *
 */
public class BeanCategoryImpl implements Serializable {
	/**
	 * 將 map 設置到 java bean (已存在的 instance) 中
	 * @param bean java bean
	 * @param attributes map
	 * @return 返回 java bean
	 */
	public Object bindBean(Object bean,Map attributes){
		if(bean instanceof Class){
			bean = ((Class)bean).newInstance()
		}
		attributes?.each { Map.Entry entry ->
			//bean."${entry.key}" = entry.value
			bean[entry.key] = entry.value
		}
		return bean
	}

	/**
	 * 判斷物件是否無內容
	 * @param obj 物件
	 * @return 是否無內容
	 */
	public boolean isEmpty(Object obj){
		if(obj == null)
			return true
		if(obj.class == String){
			String s = obj
			return s.length() == 0
		}
		if(obj instanceof Number){
			return obj == 0
		}
		if(obj instanceof Collection){
			Collection c = obj
			return c.size() == 0
		}
		if(obj instanceof Map){
			Map m = obj
			return m.size() == 0
		}
		return false
	}

	/**
	 * 取得 java bean 或 Map 的內容
	 * @param obj java bean 或 Map
	 * @param propertyName property name
	 * @param defaultValue 預設值
	 * @return property value
	 */
	public Object prop(Object obj,Object propertyName, Object defaultValue){
		if(obj == null)
			return defaultValue
		def result = obj[propertyName]
		if(result == null)
			return defaultValue
		if(result == 0)
			return defaultValue
		return result
	}
}
